1898E - Sofia and Strings - CodeForces Solution


data structures greedy strings

Please click on ads to support us..

Python Code:

def solve():
    n, m = map(int,input().split())
            a = input()
    b = input()
    
    V = [[] for _ in range(26)]

    for i in range(26):
        V[i].clear()

    for i in range(n, 0, -1):
        V[ord(a[i - 1]) - ord('a')].append(i)

    for i in range(1, m + 1):
        u = ord(b[i - 1]) - ord('a')
        if not V[u]:
            print("NO")
            return

        now = V[u].pop()

        for v in range(u):
            while V[v] and V[v][-1] < now:
                V[v].pop()

    print("YES")

t = int(input())
for _ in range(t):
        solve()

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define pll pair<ll, ll>
using namespace std;
const int mod = 1e9 + 7;
const int N = 2e5 + 7;
ll n, m;

void Z()
{
    cin >> n >> m;
    string a,b;
    cin >> a >> b;
    set<int> s[26];
    for (int i = 0;i < n;i ++)
    {
        s[a[i] - 'a'].insert(i);
    }

    for (auto x:b)
    {
        if (!s[x - 'a'].size())
        {
            cout << "No" << "\n";
            return;
        }
        int pos = *s[x - 'a'].begin();
        s[x - 'a'].erase(*s[x - 'a'].begin());
        int len = x - 'a';
        for (int i = 0;i < len;i ++)
        {
            while (!s[i].empty() && *s[i].begin() < pos)
            {
                s[i].erase(*s[i].begin());
            }
        }

    }
    cout << "Yes" << "\n";
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    cin >> t;
    while (t--)
    {
        Z();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

742A - Arpa’s hard exam and Mehrdad’s naive cheat
1492A - Three swimmers
1360E - Polygon
1517D - Explorer Space
1230B - Ania and Minimizing
1201A - Important Exam
676A - Nicholas and Permutation
431A - Black Square
474B - Worms
987B - High School Become Human
1223A - CME
1658B - Marin and Anti-coprime Permutation
14B - Young Photographer
143A - Help Vasilisa the Wise 2
320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales
734B - Anton and Digits
1080A - Petya and Origami
1642D - Repetitions Decoding
1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing